package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const BaiduMapAPIKey = "B4XhrgwA8pu7za3UuFdni56lco0G1SIB"

type BaiduIPLocationResponse struct {
	Status  int    `json:"status"`
	Address string `json:"address"`
	Content struct {
		Address       string `json:"address"`
		AddressDetail struct {
			Province string `json:"province"`
			City     string `json:"city"`
		} `json:"address_detail"`
	} `json:"content"`
}

// GetLocationFromIP retrieves location information from an IP address using Baidu Maps API
func GetLocationFromIP(ip string) (string, error) {
	url := fmt.Sprintf("https://api.map.baidu.com/location/ip?ak=%s&ip=%s", BaiduMapAPIKey, ip)

	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result BaiduIPLocationResponse
	if err := json.Unmarshal(body, &result); err != nil {
		return "", err
	}

	// Check if the API request was successful
	if result.Status != 0 {
		return "", fmt.Errorf("Baidu Maps API error, status: %d", result.Status)
	}

	return result.Content.AddressDetail.Province, nil
}
